import instance from './config'
import { apiCodes } from "@/axios/apiCodes";

const request = (method, params, config = {}) => {
  let url = params.url
  let data = params.data
  let token = ''

  let requestUrl = url
  // 路径内参数处理，如 /crp/user/{id}/detail 这类接口
  const pathQueryList = (url.match(/{\w*}/g) || []).map(field => field.slice(1, -1))
  if(pathQueryList.length) {
    pathQueryList.forEach(arg => {
      requestUrl = url.replace(`{${arg}}`, data[arg])
    })
  }

  // 所有参数添加至请求路径中
  if(config.isUrlParams) {
    let paramUrl = Object.keys(data).map(key => (encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))).join('&')
    requestUrl = requestUrl + '?' + paramUrl
  }

  // 根据请求处理参数字段
  let body = ''
  if( ['GET', 'DELETE'].includes(method)) {
    body = 'params'
  } else if(['POST', 'PUT'].includes(method)) {
    body = 'data'
  }

  const requestConfig = {
    method,
    [body]: data,
    responseType: config.responseType || '',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      Authorization: 'Bearer ' + token,
      ...params.header
    }
  }
  return new Promise((resolve, reject) => {
    instance(requestUrl, requestConfig)
      .then(res => {
      if(res.code === apiCodes.SUCCESS_CODE) {
        resolve(res)
      } else {
        reject(res)
      }
    })
      .catch(err => {
        reject(err)
      })
  })
}
export default {
  get: (params, config = {}) => {
    return request('GET', params, config)
  },
  post: (params, config= {}) => {
    return request('POST', params, config)
  },
  delete: (params, config= {}) => {
    return request('DELETE', params, config)
  },
  put: (params, config= {}) => {
    return request('PUT', params, config)
  }
}
